<template>
  <div class="project-change">
    <div class="project-change-title">ICT项目变更审批</div>
    <div class="flex">
      <div style="flex: 1">
        <!-- 项目基本信息 -->
        <div class="desc-item">
          <div class="form-item">项目基本信息</div>
          <el-descriptions class="mb-16" :column="2" :border="true">
            <el-descriptions-item v-for="(descItem, index) in projectBasicDescs" :key="index" :label="descItem.label"
              label-class-name="desc-label" :class-name="'desc-content-2'">
              <span>
                {{ descItem.content }}
              </span>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <!-- 变更字段 -->
        <div class="desc-item">
          <div class="form-item">项目变更信息</div>
          <div class="project-changes">
            <div v-for="stage in stageConfigs" :key="stage.key">
              <!-- 只有当该环节有变更记录时才显示 -->
              <template v-if="getStageChanges(stage.key).length > 0">
                <div class="table-title">{{ stage.title }}</div>
                <el-table :data="getStageChanges(stage.key)" style="width: 100%; margin-bottom: 20px">
                  <el-table-column label="字段名" width="180">
                    <template #default="{ row }">
                      {{ getFieldLabel(stage.key, row.field_name) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="old_value" label="原值" width="180">
                    <template #default="{ row }">
                      {{ tableCellFormatter(row.field_name, row.old_value) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="old_value" label="原值" width="180">
                    <template #default="{ row }">
                      {{ tableCellFormatter(row.field_name, row.new_value) }}
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </div>
            <div v-if="Object.keys(newAutonomousData).length > 0">
              <div class="table-title" > 自主能力信息 </div>
              <div class="autonomous-comparison">
                <!-- 对比容器 -->
                <div class="comparison-container">
                  <!-- 旧值 -->
                  <div class="version-box old-version">
                    <div class="version-label">
                      <el-tag type="info">原值</el-tag>
                    </div>
                    <AutonomousAbilitySelector
                      :descriptions="oldAutonomousData"
                      :readOnly="true"
                      class="data-panel"
                    />
                  </div>
                  
                  <!-- 新值 -->
                  <div class="version-box new-version">
                    <div class="version-label">
                      <el-tag type="success">新值</el-tag>
                    </div>
                    <AutonomousAbilitySelector
                      :descriptions="newAutonomousData"
                      :readOnly="true"
                      class="data-panel"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>


          <!-- 变更原因 -->
          <div class="change-reason">
            <div class="table-title">变更原因</div>
            <el-input v-model="changeReason" type="textarea" :rows="3" disabled />
          </div>

          <!-- 提交按钮 -->
          <div v-if="isShowApprovalOperation('first')">
            <div class="mb-16 flex approval-button">
              <el-button class="ml-auto" type="danger" size="default"
                @click="approvalProcess('refuse', 'constructionDepartmentManager', projectInfo.project_supervisor_id)">驳回</el-button>
              <el-button type="primary" size="default"
                @click="approvalProcess('agree', 'constructionDepartmentManager', projectInfo.project_supervisor_id)">同意</el-button>
            </div>
          </div>
          <div v-if="isShowApprovalOperation('second')">
            <div class="mb-16 flex approval-button">
              <el-button class="ml-auto" type="danger" size="default"
                @click="approvalProcess('refuse', 'projectSupervisor', 0)">驳回</el-button>
              <el-button type="primary" size="default"
                @click="approvalProcess('agree', 'projectSupervisor', 0)">同意</el-button>
            </div>
          </div>
        </div>
      </div>
      <!-- 审批流程 -->
      <div class="timeline">
        <el-timeline style="max-width: 600px; padding-left:10px">
          <el-timeline-item v-for="(process, index) in processList" :key="index"
            :color="approvalFontColor[process.status]" placement="top">
            <slot name="timestamp">
              <div class="timeline-title">
                {{ process.name }}
                <el-tag color="#ecf5ff" :style="{ color: approvalFontColor[process.status] }">{{
                  approvalStatusObj[process.status]
                }}</el-tag>
              </div>
            </slot>
            <el-card>
              <p>处理人：{{ process.assignee_user.nickname }}</p>
              <p>创建时间：{{ formatDate(process.create_time) }}</p>
              <p>审批时间：{{ formatDate(process.end_time) }}</p>
              <p>审批意见：{{ process.reason }}</p>
            </el-card>
          </el-timeline-item>
          <el-timeline-item v-for="(process, index) in processChangeProcess" :key="index" :color="process.color"
            placement="top">
            <slot name="timestamp">
              <div class="timeline-title">
                {{ process.name }}
                <el-tag color="#ecf5ff" :style="{ color: process.color }">{{
                  process.status
                }}</el-tag>
              </div>
            </slot>
            <el-card>
              <p>发起人：{{ process.assigneeUsername }}</p>
              <p>发起时间：{{ formatDate(process.createTtime) }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import * as KmsApi from '@/api/project/kms'
import * as BpmApi from '@/api/project/bpm'
import * as IctApi from '@/api/project/ict'
import { staticData } from '@/views/project/mixins/staticDataMixin'
import { projectChangeDescriptionFileds } from '@/views/project/projectChange/mixins/projectChangeKeysMixin'
import { formatDate } from '@/utils/formatTime'
import { useRoute } from 'vue-router'
import { ref, onBeforeMount } from 'vue'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { projectGradingDescriptionFileds } from '@/views/project/projectDetails/mixins/projectGradingDetailsMixin'
import AutonomousAbilitySelector from '@/views/project/projectDetails/components/AutonomousAbilitySelector.vue';
import { tableCellFormatter } from '@/views/project/utils/formatters';

onBeforeMount(async () => {
  await getApprovalProcess()
  await getProjectInfo()
  await getProjectChangeInfo()
})

// data
// 路由
const route = useRoute()
// 获取当前登录用户
const { wsCache } = useCache()
const currentUser = wsCache.get(CACHE_KEY.USER).user

// 静态变量
const { approvalStatusObj, approvalFontColor } = staticData()
const { formatAutonomousType } = projectGradingDescriptionFileds({})

// 流程列表
let processList = ref([])
// 项目信息
let projectInfo = reactive({})

const projectCode = route.query.project_code;
const changeKey = route.query.change_key;
const processInstanceId = route.query.process_instance_id
const projectAllchangeInfo = ref({})
const currentProjectChangeRecordInfo = ref([])


// 变更相关数据
const changeReason = ref('')
const oldAutonomousData = ref({});
const newAutonomousData = ref({});


const projectChangeKeys = reactive({
  projectTransferKeysDesc: [],
  projectGradingKeysDesc: [],
  startupReportingKeysDesc: [],
  testRunKeysDesc: [],
  projectDeliveryKeysDesc: []
})

const projectBasicDescs = computed(() => [
  {
    label: '项目名称',
    content: projectInfo.project_name
  },
  {
    label: '项目管理单位',
    content: projectInfo.project_management_department
  },
  {
    label: '项目编号',
    content: projectInfo.project_number
  },
  {
    label: '项目核算化编码',
    content: projectInfo.project_code
  },
  {
    label: '建设单位',
    content: projectInfo.region
  },
  {
    label: '省端项目主管',
    content: projectInfo.project_supervisor
  }
])

const processChangeProcess = computed(() => [
  {
    status: '已发起',
    color: approvalFontColor[2],
    name: '交付经理发起变更',
    assigneeUsername: projectInfo.construction_project_manager,
    createTtime: currentProjectChangeRecordInfo.value?.[0]?.timestamp
  }
])

const taskList = {
  first: '建设单位部门经理审批',
  second: '省端项目主管审批'
}

// 环节配置
const stageConfigs = [
  {
    key: 'projectTransferKeysDesc',
    title: '项目移交'
  },
  {
    key: 'projectGradingKeysDesc',
    title: '项目定级'
  },
  {
    key: 'startupReportingKeysDesc',
    title: '项目开工'
  },
  {
    key: 'testRunKeysDesc',
    title: '试运行'
  },
  {
    key: 'projectDeliveryKeysDesc',
    title: '项目交付'
  }
]

// 获取项目基本信息
const getProjectInfo = async () => {
  const params = {
    project_code: projectCode
  }
  try {
    KmsApi.getProjectInfo(params).then((res) => {
      Object.assign(projectInfo, res)
      KmsApi.getProjectDocInfo(params).then((docRes) => {
        projectInfo.files = docRes || []
        KmsApi.getTeamMembersInfo(params).then((membersRes) => {
          projectInfo.members = membersRes || []
          KmsApi.getExecuteProgressInfo(params).then((progressRes) => {
            projectInfo.progress = progressRes || []
            KmsApi.getReviewInfo(params).then((reviewRes) => {
              projectInfo.reviewInfo = reviewRes || []
              Object.assign(projectChangeKeys, reactive(projectChangeDescriptionFileds(projectInfo)))
            })
          })
        })
      })

    })
  } catch (error) {
    console.error('项目基本信息获取错误:', error)
  }
}

// 获取审批流程信息
const getApprovalProcess = async () => {
  const params = {
    processInstanceId: processInstanceId
  }
  await BpmApi.getApprovalProcessList(params).then((res) => {
    processList.value = res
  })
}

const extractAutonomousData = (changeList) => {
  const oldData = {};
  const newData = {};

  changeList.forEach(item => {
    if (item.field_name === 'autonomous_type') {
      // 保持原始字段名（带 autonomous_ 前缀）
      oldData[item.field_name] = formatAutonomousType(item.old_value);
      newData[item.field_name] = formatAutonomousType(item.new_value);
    } else if (item.field_name.startsWith('autonomous_')) {
      // 保持原始字段名（带 autonomous_ 前缀）
      oldData[item.field_name] = item.old_value;
      newData[item.field_name] = item.new_value;
    }
  });


  oldAutonomousData.value = oldData;
  newAutonomousData.value = newData;
}

// 获取项目变更信息
const getProjectChangeInfo = async () => {
  const params = {
    project_code: projectCode
  }
  await IctApi.getAllChangeListByProjectCode(params).then((res) => {
    projectAllchangeInfo.value = res
    currentProjectChangeRecordInfo.value = projectAllchangeInfo.value[changeKey]
    changeReason.value = currentProjectChangeRecordInfo.value[0].change_reason
    extractAutonomousData(currentProjectChangeRecordInfo.value)
  })
}

// 获取指定环节的变更记录
const getStageChanges = (stageKey) => {
  const stageFields = projectChangeKeys[stageKey].map(item => item.filed)
  const stageChanges = currentProjectChangeRecordInfo.value.filter(record =>
    stageFields.includes(record.field_name)
  )
  return stageChanges
}

// 获取字段的显示名称
const getFieldLabel = (stageKey, fieldName) => {
  const field = projectChangeKeys[stageKey].find(item => item.filed === fieldName)
  return field ? field.label : fieldName
}

// 判断是否展示当前审批操作
const isShowApprovalOperation = (currentTask) => {
  const currentProcess = processList.value[0]
  if (currentProcess && currentProcess.name === taskList[currentTask]) {
    if (currentUser.id === currentProcess?.assignee_user.id && [0, 1].includes(currentProcess?.status)) {
      return true
    }
  }
  return false
}

const approvalProcess = (result, currentRole, nextRoleId) => {
  ElMessageBox.confirm(`是否${result === 'agree' ? '同意' : '驳回'}该流程单？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    if (result === 'agree') {
      const agreeProcessData = {
        assignedUserIds: [nextRoleId],
        id: processList.value[0].id,
        reason: '同意',
        copyUserIds: [],
        variables: {}
      }

      if (currentRole === 'constructionDepartmentManager') {
        await IctApi.agreeProjectChangeDepartmentManagerProcess(agreeProcessData).then(() => {
        })
      } else {
        const changeList = currentProjectChangeRecordInfo.value.map(item => ({
          field_name: item.field_name,
          old_value: item.old_value,
          new_value: item.new_value
        }));
        const agreeData = {
          project_index_do: projectInfo,
          change_list: changeList,
          task_approve_req_vo: agreeProcessData
        }
        await IctApi.agreeProjectChangeSupervisorProcess(agreeData).then(() => {
          getApprovalProcess()
        })
      }
    } else if (result === 'refuse') {
      const refuseData = {
        id: processList.value[0].id,
        reason: '不同意'
      }
      await IctApi.refuseProjectChangeProcess(refuseData).then(() => {
        getApprovalProcess()
      })
    }
    ElMessage({
      type: 'success',
      message: '提交成功'
    })
  })
}
</script>

<style lang="scss" scoped>
@import url('@/views/project/projectDetails/styles/transfer.css');

.project-change {
  width: 100%;

  &-title {
    text-align: center;
    font-weight: 600;
    font-size: 24px;
    margin-bottom: 20px;
  }

  .timeline {
    background: #ffffff;
    box-shadow: 0px 0px 10px 0px #dbdbdb;
    margin-left: 16px;
    padding: 16px 24px;
    overflow: auto;

    .timeline-title {
      align-items: center;
      font-weight: 600;
      padding-bottom: 4px;
    }
  }
}

.change-reason {
  margin-top: 20px;
}

.approval-button {
  margin-top: 20px;
  text-align: center;
}

.form-item {
  margin-bottom: 15px;
}

.desc-item {
  margin-bottom: 30px;
}

.autonomous-comparison {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  background: #fff;
}

.comparison-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.version-box {
  position: relative;
  border-radius: 4px;
  padding: 15px;
}

.old-version {
  background-color: #f8f9fa;
  border-left: 4px solid #909399;
}

.new-version {
  background-color: #f0f9eb;
  border-left: 4px solid #67c23a;
}

.version-label {
  position: absolute;
  top: -12px;
  left: 10px;
  background: white;
  padding: 0 5px;
}

.data-panel {
  margin-top: 10px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .comparison-container {
    grid-template-columns: 1fr;
  }
}
</style>